package com.fuchuang.seckillsystem.service.impl;

import com.fuchuang.seckillsystem.dto.GoodsQuery;
import com.fuchuang.seckillsystem.dto.KeyConstants;
import com.fuchuang.seckillsystem.dto.TimeConstants;
import com.fuchuang.seckillsystem.entity.Activity;
import com.fuchuang.seckillsystem.entity.Goods;
import com.fuchuang.seckillsystem.exception.GlobalException;
import com.fuchuang.seckillsystem.mapper.ActivityMapper;
import com.fuchuang.seckillsystem.mapper.GoodsMapper;
import com.fuchuang.seckillsystem.service.IGoodService;
import com.fuchuang.seckillsystem.utils.MyStringUtils;
import com.fuchuang.seckillsystem.vo.RespBeanEnum;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Service
public class GoodsServiceImpl implements IGoodService {
    
    @Autowired
    private GoodsMapper goodsMapper;
    
    
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    
    
    @Resource
    private ActivityMapper activityMapper;
    
    @Override
    @Transactional
    public void addGoods(Goods goods) {
        //对参数进行校验
        checkGoodsParams(goods);
        Date date = new Date();
        java.sql.Date sqlDate = new java.sql.Date(date.getTime());
        goods.setCreateTime(sqlDate);
        goods.setUpdateTime(sqlDate);
        goods.setIsValid(1);
        try {
            goodsMapper.insertSelective(goods);
        } catch (Exception e) {
            throw new GlobalException(RespBeanEnum.GOODS_INSERT_ERROR);
        }
        //添加到redis中
        redisTemplate.opsForValue().set(KeyConstants.GOODS + goods.getId(), goods, TimeConstants.GOODS, TimeUnit.HOURS);
    }
    
    private void checkGoodsParams(Goods goods) {
        if (goods.getPrice() == null || MyStringUtils.isBlank(goods.getGoodsName())
                || MyStringUtils.isBlank(goods.getDetail()) || (goods.getType() != 1 && goods.getType() != 0)) {
            throw new GlobalException(RespBeanEnum.PARAMS_ERROR);
        }
    }
    
    
    @Override
    @Transactional
    public void deleteGoodsById(Integer goodsId) {
        if (goodsId == null || goodsId <= 0) {
            throw new GlobalException(RespBeanEnum.PARAMS_ERROR);
        }
        Goods goods = goodsMapper.selectByPrimaryKey(goodsId);
        if (Objects.isNull(goods)) {
            throw new GlobalException(RespBeanEnum.GOODS_NOT_EXIST_ERROR);
        }
        //判断商品是否在秒杀活动中，如果在，则需删除秒杀活动中的商品才能删除总的商品
        List<Activity> activityList = activityMapper.selectActivityByGoodsId(goodsId);
        if (activityList.size() != 0) {
            throw new GlobalException(RespBeanEnum.GOODS_IN_ACTIVITY);
        }
        Date date = new Date();
        java.sql.Date sqlDate = new java.sql.Date(date.getTime());
        goods.setUpdateTime(sqlDate);
        goods.setIsValid(0);
        try {
            goodsMapper.updateByPrimaryKeySelective(goods);
        } catch (Exception e) {
            throw new GlobalException(RespBeanEnum.GOODS_DELETE_ERROR);
        }
        //删除redis中数据
        redisTemplate.delete(KeyConstants.GOODS + goodsId);
    }
    
    
    @Override
    @Transactional
    public void updateGoods(@RequestBody Goods goods) {
        Goods result = goodsMapper.selectByPrimaryKey(goods.getId());
        if (Objects.isNull(result)) {
            throw new GlobalException(RespBeanEnum.GOODS_NOT_EXIST_ERROR);
        }
        List<Activity> activities = activityMapper.selectActivityByGoodsId(goods.getId());
        for (Activity activity : activities) {
            if (activity.getStartTime().before(new Date(System.currentTimeMillis() - 10 * 60 * 1000)) && activity.getEndTime().after(new Date())) {
                throw new GlobalException(RespBeanEnum.GOODS_IN_ACTIVITY);
            }
        }
        try {
            Date date = new Date();
            java.sql.Date sqlDate = new java.sql.Date(date.getTime());
            goods.setUpdateTime(sqlDate);
            goodsMapper.updateByPrimaryKeySelective(goods);
        } catch (Exception e) {
            throw new GlobalException(RespBeanEnum.GOODS_UPDATE_ERROR);
        }
        //删除redis中数据
        redisTemplate.delete(KeyConstants.GOODS + goods.getId());
    }
    
    @Override
    public Goods selectGoodsById(Integer goodsId) {
        Goods goods = (Goods) redisTemplate.opsForValue().get(KeyConstants.GOODS + goodsId);
        if (goods == null) {
            goods = goodsMapper.selectByPrimaryKey(goodsId);
            if (Objects.isNull(goods)) {
                throw new GlobalException(RespBeanEnum.GOODS_NOT_EXIST_ERROR);
            }
            //添加到redis中
            redisTemplate.opsForValue().set(KeyConstants.GOODS + goods.getId(), goods, TimeConstants.GOODS, TimeUnit.HOURS);
        }
        return goods;
    }
    
    @Override
    public Map<String, Object> selectAllGoods(GoodsQuery goodsQuery) {
        Map<String, Object> map = new HashMap<>();
        PageHelper.startPage(goodsQuery.getPage(), goodsQuery.getLimit());
        PageInfo<Goods> pageInfo = new PageInfo<>(goodsMapper.selectAllGoods(goodsQuery));
        map.put("list", pageInfo.getList());
        map.put("count", pageInfo.getTotal());
        return map;
    }
    
    @Override
    @Transactional
    public void decreaseStock(Integer goodsId) {
        Integer rows = goodsMapper.decreaseStock(goodsId);
        if (rows != 1) {
            throw new GlobalException(RespBeanEnum.STOCK_ERROR);
        }
    }
    
    @Override
    @Transactional
    public void increaseStock(Integer goodsId) {
        Integer rows = goodsMapper.increaseStock(goodsId);
        if (rows != 1) {
            throw new GlobalException(RespBeanEnum.ORDER_CANCEL_ERROR);
        }
    }
}
